package com.wwwarehouse.resource_center.fragment.rules;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.rules.StocksBean;
import com.wwwarehouse.resource_center.bean.rules.TaskDetailedRule;
import com.wwwarehouse.resource_center.bean.rules.TaskUnitBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.Event;
import com.wwwarehouse.resource_center.eventbus_event.RulesEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/9/5.
 *         <p/>
 *         编辑任务分配规则，可修改和删除，信息卡
 */
public class EditInformationSetRulesFragment extends SetRulesFragment implements View.OnClickListener, DialogTools.ConfirmListener {

    private static final int SELECT_APPLICATION_OBJECTS = 1;
    private static final int SELECT_TASK = 2;

    public static final int QUERY_TASK_ALLOCATION_RULE = 2; //查询详细规则
    public static final int DELETE_TASK_ALLOCATION_RULE = 4;  //删除

    public static final int UPDATE_TASK_ALLOCATION_RULE = 5;  //修改保存
    private String operatorType;
    private String operatorName;
    private String valueName;
    private boolean isShowDialo  = true; //peekFragment是一样的，导致按钮重复了，触发了两个事件。以此变量控制。
    private boolean isFunction ;
    private String mTitle ;
    @Override
    protected void init(View view) {
        mLoadingView.setVisibility(View.VISIBLE);
        Bundle bundle = getArguments();
        taskAllocationUkid = bundle.getString("taskAllocationUkid");
        isFunction = bundle.getBoolean("isFunction");
        businessId = bundle.getString("businessId");

        applyBusinessList = bundle.getStringArrayList("applyBusinessId");
        super.init(view);
        ruleTitle = getString(R.string.edit_rule_name);
        mTextObject.setBackgroundColor(getResources().getColor(R.color.common_color_c12_836fdb));
        mTask.setBackgroundColor(getResources().getColor(R.color.common_color_c1_337cff));
//        mOperator.setBackgroundColor(getResources().getColor(R.color.common_color_c13_23c0b1));
        mDistributionMode.setBackgroundColor(getResources().getColor(R.color.common_color_c13_23c0b1));
        tvobject.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        tvtask.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        tvallocation.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
//        tvoperator.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        imageobject.setImageResource(R.drawable.resource_object_icon_object);
        imagetask.setImageResource(R.drawable.icon_task);
//        imgoperator.setImageResource(R.drawable.icon_operator);
        imgallocation.setImageResource(R.drawable.icon_allocation);
        ((BaseCardDeskActivity) mActivity).setTitleBt1Text(isFunction?getString(R.string.button_text_save):getString(R.string.edit_button));
        ((BaseCardDeskActivity) mActivity).setTitleBt2Text(getString(R.string.edit_photo_delete));
    }

    @Override
    protected void loadDatas() {
        if (isFunction){
            mTitle = getString(R.string.edit_task_rule);
            mTextRuleName.setOnClickListener(this);
            mTextObject.setOnClickListener(this);
            mTask.setOnClickListener(this);
            mOperator.setOnClickListener(null);
            mDistributionMode.setOnClickListener(this);
        }else {
            mTitle = getString(R.string.configuring_task_rules);
            mTextRuleName.setOnClickListener(null);
            mTextObject.setOnClickListener(null);
            mTask.setOnClickListener(null);
            mOperator.setOnClickListener(null);
            mDistributionMode.setOnClickListener(null);
        }
        mRuleScroll.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                if (isShow) {
                    //显示按钮
                    if (isFunction){
                        ((BaseCardDeskActivity) mActivity).showTitleBt2();
                    }else {
                        ((BaseCardDeskActivity) mActivity).showTitleBt1();
                    }
                } else {
                    //隐藏按钮
                    ((BaseCardDeskActivity) mActivity).hideTitleBt();
                }
                isShow = !isShow;
            }

            @Override
            public void onUpPull() {

            }
        });
    }

    @Override
    public void titleBt1Click() {
        if (peekFragment() instanceof EditInformationSetRulesFragment) {
            ((BaseCardDeskActivity) mActivity).hideTitleBt();
               isShow = true;
                if (isFunction){
                    //功能卡
                    DialogTools.getInstance().showCustomDialogPrompt(mActivity, null, getString(R.string.resource_dialog_update), true, new DialogTools.ConfirmListener() {
                        @Override
                        public void setConfirmListener(Dialog dialog, View view, String input) {
                            updateTaskAllocationRule();
                            dialog.dismiss();
                        }
                    }, "确定", "不了");

                }else {
                    //信息卡，
                    EditSetRulesFragment rulesFragment  = new EditSetRulesFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("taskAllocationUkid", taskAllocationUkid);
                    bundle.putString("businessId", businessId);
                    bundle.putStringArrayList("applyBusinessId", applyBusinessList);
                    bundle.putBoolean("isFunction", false);
                    rulesFragment.setArguments(bundle);
                    pushFragment(rulesFragment);
                }
            }
    }

    @Override
    public void titleBt2Click() {
        if (peekFragment() instanceof EditInformationSetRulesFragment){

                ((BaseCardDeskActivity) mActivity).hideTitleBt();
                isShow = true;
                DialogTools.getInstance().showCustomDialogPrompt(mActivity, null, getString(R.string.resource_dialog_delete), true, new DialogTools.ConfirmListener() {
                    @Override
                    public void setConfirmListener(Dialog dialog, View view, String input) {
                        deleteTaskAllocationRule();
                        dialog.dismiss();
                    }
                }, "确定", "不了");
            }
    }

    //修改
    protected void updateTaskAllocationRule() {
        Map<String, Object> obj = new HashMap<>();
        obj.put("applyBusinessList",StockesTypes);
        obj.put("businessId",businessId);
        Map<String, Object> cfTaskAllocate = new HashMap<>();
        cfTaskAllocate.put("allocateTactics",allocateTactics);
        cfTaskAllocate.put("maxTaskNum",maxTaskNum);
        cfTaskAllocate.put("ruleName",mRuleName);
        cfTaskAllocate.put("taskAllocateUkid",taskAllocationUkid);
        obj.put("cfTaskAllocate",cfTaskAllocate);
        ArrayList< Map<String, Object>>  arrayList = new ArrayList<>();
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("conditionCode","is_work");
        conditions.put("valueCode","yes_work");
        arrayList.add(conditions);
        obj.put("conditions",arrayList);
        obj.put("operatorType","HUMAN");
        obj.put("taskTypes",taskTypes);
        httpPost(ResourceConstant.UPDATE_TASK_ALLOCATION_RULE,obj,UPDATE_TASK_ALLOCATION_RULE,true,"");
    }


    //删除
    protected void deleteTaskAllocationRule() {
        Map<String, Object> obj = new HashMap<>();
        obj.put("businessId",businessId);
        obj.put("taskAllocateUkid",taskAllocationUkid);
        httpPost(ResourceConstant.DELETE_TASK_ALLOCATION_RULE,obj,DELETE_TASK_ALLOCATION_RULE,true,"");
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof EditInformationSetRulesFragment)
            mActivity.setTitle(mTitle);
    }
    @Override
    public void requestDatas() {
        Map<String, Object> map = new HashMap<>();
        map.put("taskAllocationUkid", taskAllocationUkid); //查询详细规则
        httpPost(ResourceConstant.QUERY_TASK_ALLOCATION_RULE, map, QUERY_TASK_ALLOCATION_RULE, true, null);
    }

    @Override
    public void onReLoad(int code) {

    }

//    public void onEventMainThread(RulesEvent event) {
//        switch (event.getCode()) {
//            case RulesEvent.RULE_NAME:
//                if (event.getMsg().equals("RULE_NAME")) {
//                    ruleName.setText((String) event.getData());
//                }
//                break;
//            case RulesEvent.RULE_BUSINESSIDS:
//
//
//                break;
//            case RulesEvent.RULE_TASK:
//
//                 if (event.getMsg().equals("RULE_TASK")){
//
//                }
//                break;
//            case RulesEvent.RULE_OPERATOR:
//                Map<String, Object> objectMap = (Map<String, Object>) event.getData();
//                ArrayList<AllocationConditionBean> conditionBeen = (ArrayList<AllocationConditionBean>) objectMap.get("conditions");
//                ArrayList<OperatorTypeBean> typeBeen = (ArrayList<OperatorTypeBean>) objectMap.get("typeBeen");
//                if (typeBeen != null) {
//                    for (int i = 0; i < typeBeen.size(); i++) {
//                        if (typeBeen.get(i).isSelect()) {
//                            operatorType = typeBeen.get(i).getCode();
//                            operatorName = typeBeen.get(i).getName();
//                            break;
//                        }
//                    }
//                }
//                if (conditionBeen != null) {
//                    for (int i = 0; i < conditionBeen.size(); i++) {
//                        List<AllocationConditionBean.ConditionValuesBean> conditionValues = conditionBeen.get(i).getConditionValues();
//                        conditionCode = conditionBeen.get(i).getConditionCode();
//                        for (int i1 = 0; i1 < conditionValues.size(); i1++) {
//                            if (conditionValues.get(i1).isSelect()) {
//                                valueCode = conditionValues.get(i1).getValueCode();
//                                valueName = conditionValues.get(i1).getValueName();
//                                break;
//                            }
//                        }
//                    }
//                }
//                LogUtils.showInfoLog("operatorType:" + operatorType + "operatorName:" + operatorName);
//                tvoperator.setText(operatorName + "、" + valueName);
//
//                break;
//            case RulesEvent.RULE_ALLOCATETACTICS:
//                OperatorTypeBean type = (OperatorTypeBean) event.getData();
//                allocateTactics = type.getCode();
//                maxTaskNum = event.getMsg();
//                tvallocation.setText(type.getName() + "、" + "饱和度<" + maxTaskNum);
//                break;
//        }
//
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_APPLICATION_OBJECTS:

                break;
            case SELECT_TASK:

                break;
        }
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what) {
            case ADD_TASK_ALLOCATION_RULE:  //新增
                if (TextUtils.equals("0", commonClass.getCode())) {
//                        ArrayList<SearchTaskRule> searchTaskRule = (ArrayList<SearchTaskRule>) JSON.parseArray(commonClass.getData().toString(), SearchTaskRule.class);
//                        if (searchTaskRule.size() > 0) {
//
//                            DialogTools.getInstance().showCustomWarning(mActivity, getString(R.string.cannot_build_new), getString(R.string.prompt_content), false, SetRulesFragment.this);
//                        } else {
//                            mRecyclerView.setVisibility(View.GONE);
//                            mTask.setVisibility(View.VISIBLE);

//                        }
                } else {
                    toast(commonClass.getMsg());
                }
                break;
            case QUERY_TASK_ALLOCATION_RULE:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    TaskDetailedRule rule = JSON.parseObject(commonClass.getData().toString(), TaskDetailedRule.class);
                    businessId = rule.getBelongBusinessUkid();
                    //规则名字
                    ruleName.setText(rule.getRuleName());
                    mRuleName = rule.getRuleName();
                    //任务
                    List<TaskDetailedRule.TaskTypesBean> taskTypes = rule.getTaskTypes();
                    String jsonString = JSON.toJSONString(taskTypes);
                    mTasksListBean = (ArrayList<TaskUnitBean.DataBean.ListBean>) JSON.parseArray(jsonString, TaskUnitBean.DataBean.ListBean.class);
                    total = mTasksListBean.size();
                    setTask(mTasksListBean);
                    //应用对象
                    List<TaskDetailedRule.StockListBean> warehouse = rule.getStockList();
                    String warehouseString = JSON.toJSONString(warehouse);

                    Log.d("warehouseString",warehouseString);
                    mStocksListBean = (ArrayList<StocksBean.ListBean>) JSON.parseArray(warehouseString, StocksBean.ListBean.class);
                    setStock(mStocksListBean);

                    //操作者
                    List<TaskDetailedRule.RulesBean> rules = rule.getRules();
                    operatorType = rules.get(0).getOperatorCode();
                    operatorName = rules.get(0).getOperator();
                    conditionCode = rules.get(0).getConditionCode();
                    valueCode = rules.get(0).getItemCode();
                    valueName = rules.get(0).getItemName();
//                    tvoperator.setText(operatorName + "、" + valueName);
                    //分配策略，饱和度
                    maxTaskNum = rule.getTaskMaxNum()+"";
                    allocateTactics = rule.getAllocateTacticsCode();
                    allocateTacticsName = rule.getAllocateTactics();
                    tvallocation.setText( allocateTacticsName+ "、" + "饱和度<" + maxTaskNum);
                }else if (TextUtils.equals("60011", commonClass.getCode())){
                    mLoadingView.setVisibility(View.VISIBLE);
                    mTextRuleName.setOnClickListener(null);
                    mTextObject.setOnClickListener(null);
                    mTask.setOnClickListener(null);
                    mOperator.setOnClickListener(null);
                    mDistributionMode.setOnClickListener(null);
                    mRuleScroll.setOnPullListener(null);
                    EventBus.getDefault().post(new Event(RulesEvent.RULE_REFRESH));
                    mLoadingView.showSystemView(commonClass.getMsg(),true);
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            popFragment();
                        }
                    }, 2500);
                    mLoadingView.setSystemListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mLoadingView.showProgressView(true);
                        }
                    });

                } else {
                    mRuleScroll.setOnPullListener(null);
                    mLoadingView.setVisibility(View.VISIBLE);
                    mLoadingView.showSystemView(true);
                    mLoadingView.setSystemListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mLoadingView.showProgressView(true);
                            requestDatas();
                        }
                    });
                }
                break;
            case DELETE_TASK_ALLOCATION_RULE:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    popFragment();
                    popFragment();
                    ConfigurationSuccessFragment successFragment = new ConfigurationSuccessFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("success", "DELETE");
                    successFragment.setArguments(bundle);
                    pushFragment(successFragment);
                    //通知刷新
                    EventBus.getDefault().post(new Event(RulesEvent.RULE_REFRESH));

                }else if (TextUtils.equals("60011", commonClass.getCode())){
                    EventBus.getDefault().post(new Event(RulesEvent.RULE_REFRESH));
                    toastAtTop(commonClass.getMsg());
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            popFragment();
                        }
                    }, 2500);
                }
                else {
                    DialogTools.getInstance().showCustomWarning(mActivity, getString(R.string.dialog_1_title), commonClass.getMsg(), false, EditInformationSetRulesFragment.this);
                }

                break;

            case UPDATE_TASK_ALLOCATION_RULE:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    //通知刷新
                    popFragment();
                    ConfigurationSuccessFragment successFragment = new ConfigurationSuccessFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("success", "UPDATE");
                    successFragment.setArguments(bundle);
                    pushFragment(successFragment);
                    EventBus.getDefault().post(new Event(RulesEvent.RULE_REFRESH));
                } else if (TextUtils.equals("60010", commonClass.getCode())){
                    DialogTools.getInstance().showCustomWarning(mActivity, getString(R.string.dialog_1_title), commonClass.getMsg(), false, new DialogTools.ConfirmListener() {
                        @Override
                        public void setConfirmListener(Dialog dialog, View view, String input) {
                            dialog.dismiss();
                            //任务
                            SelectTaskParentFragment fragment = new SelectTaskParentFragment();
                            Bundle  bundle = new Bundle();
                            bundle.putString("businessId",businessId);
                            bundle.putParcelableArrayList("mSelectTasksListBean",  mTasksListBean);
                            fragment.setArguments(bundle);
                            pushFragment(fragment);
                        }
                    });
                }else if (TextUtils.equals("60011", commonClass.getCode())){
                    EventBus.getDefault().post(new Event(RulesEvent.RULE_REFRESH));
                    toastAtTop(commonClass.getMsg());
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            popFragment();
                        }
                    }, 2500);
                }
                else {
                    DialogTools.getInstance().showCustomWarning(mActivity, getString(R.string.dialog_1_title), commonClass.getMsg(), false, EditInformationSetRulesFragment.this);
                }
                break;
            case QUERY_TASK_ALLOCATION_RULEALL: //业务单位对应所有规则详情(信息卡片) TaskDetailedRule
                ArrayList<TaskDetailedRule> desks = (ArrayList<TaskDetailedRule>) JSON.parseArray(commonClass.getData().toString(), TaskDetailedRule.class);


                break;
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        ((BaseCardDeskActivity) mActivity).hideTitleBt();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void setConfirmListener(Dialog dialog, View view, String input) {
        dialog.dismiss();

    }

    class RuleAdapter extends RecyclerView.Adapter<RuleAdapter.ViewHolder> {

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View arg0) {
                super(arg0);
            }

            ImageView mImag;
            TextView mTxtTaskName;
            TextView mTxtNumber;

        }

        @Override
        public int getItemCount() {
            return mCount;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.rule_task_item, viewGroup, false);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
            //获取当前控件的布局对象
            params.width = (mRecyclerView.getWidth() - (getItemCount() - 1) * ConvertUtils.dip2px(mActivity, 5)) / getItemCount();//设置当前控件布局的宽度和margin
            view.setLayoutParams(params);//将设置好的布局参数应用到控件中
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.mTxtTaskName = (TextView) view
                    .findViewById(R.id.task_name);
            viewHolder.mTxtNumber = (TextView) view
                    .findViewById(R.id.task_num);
            viewHolder.mImag = (ImageView) view
                    .findViewById(R.id.task_img);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    startActivityForResult(SelectTaskActivity.class,SELECT_TASK,new Bundle());
                }
            });
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            viewHolder.mTxtTaskName.setText("退货");
            viewHolder.mTxtNumber.setText("退货点数");

        }
    }
}
